﻿using Microsoft.Extensions.Options;
using MySql.Data.MySqlClient;
using Summer.IService.core;
using Summer.Model.core;
using Summer.Model.enums;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;

namespace Summer.Service.core
{
    public class DbFactory:IDbFactory
    {
        readonly IOptions<DbOption> _options;

        public DbFactory(IOptions<DbOption> options)
        {
            _options = options;
        }

        /// <summary>
        /// 创建数据库连接
        /// </summary>
        /// <returns></returns>
        public DbConnection Create()
        {
            DbConnection cnn = null;
            DbOption dbOption = _options.Value;
            switch (dbOption.DbModel)
            {
                case DbModel.MySQL:
                    cnn = new MySqlConnection(dbOption.ConnectionString);
                    Dapper.SimpleCRUD.SetDialect(Dapper.SimpleCRUD.Dialect.MySQL);//因为mysql语句不支持中括号，加上这个设置避免报错
                    break;
                case DbModel.SQLServer:
                    cnn = new SqlConnection(dbOption.ConnectionString);
                    break;
                default:
                    throw new Exception("please specify DbModel!");
            } 
            return cnn;
        }
    }
}
